package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.PointRecords;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface PointRecordsRepository extends JpaRepository<PointRecords, Long> {

    List<PointRecords> findByUseridOrderByCreatedAtDesc(Long userid);

    @Query("select count(r) from PointRecords r where r.userid = ?1 and r.sourceType = ?2 and r.createdAt >= :startOfDay")
    Long countTodayRecordsByType(Long userid, String sourceType, LocalDateTime startOfDay);

    default Long countTodayRecordsByType(Long userid, String sourceType) {
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        return countTodayRecordsByType(userid, sourceType, startOfDay);
    }

    @Query("select count(pr) from PointRecords pr where pr.userid = ?1 and pr.sourceType = ?2 and pr.createdAt between ?3 and ?4")
    Long countByUseridAndSourceTypeAndCreatedAtBetween(Long userid, String sourceType, LocalDateTime start, LocalDateTime end);

    void deleteByUserid(Long userId);

    @Modifying
    @Query(value = "CALL redeem_reward(:p_userid, :p_reward_id, :p_quantity)", nativeQuery = true)
    void redeemReward(
            @Param("p_userid") Long userId,
            @Param("p_reward_id") Long rewardId,
            @Param("p_quantity") Integer quantity
    );
}